<?php
/**
 * 关键字
 * User: wayne
 * Date: 2015-09-08
 */
namespace Operate\Model;
use Think\Model;

class WxKeywordModel extends Model {

//     protected $tableName = 'wx_rule';

//     protected $_validate = array(
//         array('mcontent', 'require', 1),
//         array('rule_name','require','规则名称已存在',1,'unique'), // 在新增的时候验证name字段是否唯一
//         array('value','0,9','规则级别非法',1,'between'), // 当值不为空的时候判断是否在一个范围内
//     );


    /**
     * 获取改公众号的关键字规则
     *
     * @param integer $mp_id
     */
    public function getKeywordJoinRule($mp_id) {
        $time = date('Y-m-d H:i:s');

        $sql = "select k.keyword,k.match_type,r.rule_id,r.rule_name,r.open_score,r.has_deadline,r.expire_start_time,r.expire_end_time,r.content_type,r.reply_text,r.reply_materialid,r.`status`
        from {$this->tablePrefix}wx_keyword as k left join {$this->tablePrefix}wx_rule as
        r on k.rule_id=r.rule_id where r.mp_id = {$mp_id} and r.status = 1 order by r.rule_weight ASC";
        return $this->query($sql);
    }



    /**
     * 更新规则
     * @name ruleInsert
     * @param array $data
     * @param array $keywords
     * @return boolean
     */
    public function ruleUpdate($data=array(), $keywords){
        if(false == $data['id']){
            $data['id'] = $this->add($data);
        }else{
            $this->save($data);
        }
        if(is_array($keywords) && count($keywords)>0){
            return $this->keywordUpdate($data['id'], $keywords);
        }
        return false;
    }

    /**
     * 更新关键词数据
     * @name keywordUpdate
     * @param int $ruleId
     * @reuturn mixed
     */
    protected function keywordUpdate($ruleId, $data){
        $this->query("delete from __WX_KEYWORD__ where rule_id=$ruleId");
        foreach($data as $key => $val){
            $this->query("insert into __WX_KEYWORD__ (keyword,match_type,rule_id) values ('{$val['keyword']}','{$val['match_type']}', '{$ruleId}')");
        }
        return true;
    }

    /**
     * 关键词列表
     * @name keywordList
     */
    public function keywordList($inputParams){
        $pageInfo = $orderInfo = $condition = $data = array();
        if($inputParams['page']){
            $pageInfo = $inputParams['page'];
        }
        if($inputParams['order']){
            $orderInfo = $inputParams['order'];
        }
        if($inputParams['condition']){
            $condition = $inputParams['condition'];
        }
        //todo page
        $data['list'] = $this->field('*')->where($condition)->order($orderInfo)->limit($pageInfo)->select();
        return $data;
    }
    
    public function deleteById($keyword_id) {
        return $this->where(array('keyword_id' => $keyword_id))->delete();
    }
    
    public function deleteByRuleid($rule_id) {
        return $this->where(array('rule_id' => $rule_id))->delete();
    }
}